package com.example.demo.service;

import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import com.example.demo.dto.AIAnswerDTO;
import com.example.demo.request.ChatRequest;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import reactor.core.publisher.Flux;


@Service
public class TYService {

    private final RestTemplate restTemplate;
    private WebClient webClient;
    
    public TYService() {
        this.restTemplate = new RestTemplate();
    }

    // public String chatWithFlask(String userInput) {
    //     String url = "http://localhost:9121/chat";  // Flask 聊天接口地址
    //     ChatRequest request = new ChatRequest(userInput);
    //     return restTemplate.postForObject(url, request, String.class);
    // }
    //用于读取第三方的返回结果
    private ObjectMapper objectMapper = new ObjectMapper();

    @PostConstruct
    public void postConstruct() {
        this.webClient = WebClient.builder()//创建webflux的client
                .baseUrl("http://localhost:9121")//填写对应的api地址
                .defaultHeader("Content-Type", "application/json")//设置默认请求类型
                .build();
    }
        //请求stream的主题
    public Flux<AIAnswerDTO> ChatStream(String userinput) {
        //构建请求json
        // 创建一个包含用户输入的 Map
        Map<String, String> inputMap = new HashMap<>();
        inputMap.put("userinput", userinput);

        // 使用 JSONUtil 将 Map 转换为 JSON 字符串
        String paramJson = JSONUtil.toJsonStr(inputMap);
        // String paramJson = objectMapper.writeValueAsString(Collections.singletonMap("userinput", userinput));
        System.out.println("请求参数：" + paramJson);
        //使用webClient发送消息
        return this.webClient.post()
                .uri("/chat")//请求uri
                // .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(paramJson))
                .retrieve()
                .bodyToFlux(String.class)
                .flatMap(result -> handleWebClientResponse(result));//接收到消息的处理方法
    }

    private Flux<AIAnswerDTO> handleWebClientResponse(String resp) {
        if (StrUtil.equals("\n\n",resp)){// \n\n是消息结束标识
            return Flux.empty();
        }

        try {
            JsonNode jsonNode = objectMapper.readTree(resp);
            // 直接提取 content 字段
            String content = jsonNode.get("content").asText();
            // System.out.println("生成的回复内容: " + content);
            
            AIAnswerDTO result = new AIAnswerDTO();
            result.setContent(content);
            
            // 如果有错误信息，设置错误字段
            if (jsonNode.has("error")) {
                result.setError(jsonNode.get("error").asText());
            }
    
            return Flux.just(result);
        } catch (Exception e) {
            throw new RuntimeException("处理响应时发生错误: " + e.getMessage());
        }
    }
    
    // 图片理解
    public String visionWithFlaskURL(String userInput, String imageUrl,boolean isUrl) {
        System.out.println("URl文件开始调用flask");
        String url = "http://localhost:9121/vision";  // Flask 视觉接口地址

        // 创建请求体 JSON
        JSONObject requestBody = new JSONObject();
        requestBody.put("input", userInput);

        // 如果是 URL，直接放入（这里假设传入的字符串是 URL）
        requestBody.put("image", imageUrl); // 传入的 URL 字符串
        requestBody.put("isUrl", isUrl); // 
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        System.out.println("URL：" + requestBody.toString());
        // 构建请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody.toString(), headers);
        System.out.println("开始发送请求");
        // 发送 POST 请求并返回结果
        return restTemplate.postForObject(url, requestEntity, String.class);
    }
    
    public String visionWithFlask(String userInput, MultipartFile imageFile, boolean isUrl) {
        System.out.println("开始调用flask");
        String url = "http://localhost:9121/vision";  // Flask 视觉接口地址

        // 创建请求体 JSON
        JSONObject requestBody = new JSONObject();
        requestBody.put("input", userInput);

        // 如果是文件，处理文件上传逻辑，比如将文件转为 Base64 编码
        String base64Image = convertFileToBase64(imageFile);
        requestBody.put("image", base64Image);
        requestBody.put("isUrl", isUrl); //

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 构建请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody.toString(), headers);
        System.out.println("开始发送请求");
        // System.out.println("请求体：" + requestEntity.getBody());

        // 发送 POST 请求并返回结果
        return restTemplate.postForObject(url, requestEntity, String.class);
    }

    private String convertFileToBase64(MultipartFile imageFile) {
        try {
            byte[] fileContent = imageFile.getBytes();  // 读取文件内容
            return Base64.getEncoder().encodeToString(fileContent); // 转换为 Base64 字符串
        } catch (IOException e) {
            e.printStackTrace();
            return null; // 或者抛出异常
        }
    }
    
}
